package eu.news.servlet.admin.news;


import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.news.data.hibernate.dao.HB_PictureDAO;
import eu.news.data.pojo.Picture;
import eu.news.kits.ImageProcesser;
import eu.web.io.upload.FileUploader;

/**
 * Servlet implementation class Upload
 */
public class UploadImage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String for_=request.getParameter("for");
		int width=10000;
		int height=60;
		if("title".equals(for_)){
			width=290;
			height=220;
		}
		String dirPath=getServletContext().getRealPath("/userdata/upload/images/");
		String thumbsPath=getServletContext().getRealPath("/userdata/upload/thumbs/")+"/";
		FileUploader upload=new FileUploader(request,dirPath);
		upload.addPermitSuffix("jpg");
		upload.addPermitSuffix("png");
		upload.addPermitSuffix("jpeg");
		upload.upload();
		if(upload.getFiles().size()<=0){
			if(upload.getDenied().size()>0)
				request.setAttribute("error", "只允许jpg，png，jpeg格式的图片");
			else if(upload.getTooBig().size()>0)
				request.setAttribute("error", "只允许2M以下的文件");
			else
				request.setAttribute("error", "未知错误");
			request.getRequestDispatcher("/admin/face/reply/upload_image_done.jsp").
				forward(request, response);
			return;
		}
		File f=upload.getFiles().get(0).getFile();
		File tf=new File(thumbsPath+f.getName());
		FileOutputStream fos=new FileOutputStream(tf);
		String ext=f.getName().substring(f.getName().lastIndexOf(".")+1);
		BufferedImage image = ImageIO.read(f);
		ImageIO.write((RenderedImage) ImageProcesser.scaleImage(image, width, height,ext),
					ext, fos);
		fos.close();
		request.setAttribute("thumb",
				tf.getCanonicalPath().replace(getServletContext().getRealPath("/"),"").
				replace('\\', '/'));
		request.setAttribute("origin",
				f.getCanonicalPath().replace(getServletContext().getRealPath("/"),"").
				replace('\\', '/'));
		HB_PictureDAO pDao=new HB_PictureDAO();
		Picture pic=new Picture();
		pic.setPath((String) request.getAttribute("origin"));
		pic.setThumb((String) request.getAttribute("thumb"));
		pDao.save(pic);
		pDao.commit();
		request.setAttribute("id", pic.getId());
		request.getRequestDispatcher("/admin/face/reply/upload_image_done.jsp").
			forward(request, response);
	}

}
